import { Tooltip, Pagination, MenuProps, Modal, Button, ConfigProvider, Input, Table, Space, Select, Form, DatePicker } from 'antd';
import {
    ClockCircleOutlined,
    FileTextOutlined,
    PlusOutlined,
    ExportOutlined,
    EditOutlined,
    DeleteOutlined,
    CopyOutlined,
    ExclamationCircleOutlined,
    UndoOutlined,
    SearchOutlined,
    BookOutlined,
    InfoCircleOutlined,
    FileSyncOutlined,
    UnorderedListOutlined
} from '@ant-design/icons'
import { ChangeEvent, forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import systemApi from '../../../api/system';
import { addKeyToList, checkIsTempAccount, commonErrorMsg, deepCloneV2, formatTime, getAZindex, getChangeEventValue, getSingleTdTableHeight, handleJumpEditPage, isEmpty, makeClassNameList, provinceList, toastShort } from '../../../utils';
import { DocInstance } from '../../../utils/types';
import AddProjectModal from '../modal/AddProjectModal';
import LoadingWapper from '../../../components/loading/LoadingWapper';
import EmptyWapper from '../../../components/loading/EmptyWapper';
import { ColumnsType } from 'antd/es/table';
import useReSize from '../../../hooks/useResize';
import Pinyin from '../../../utils/pinyin';
import CopyProjectModal from '../modal/CopyProjectModal';
import { Delete, Editor } from '@icon-park/react';

interface Props {
    screenType: 'recently-opened' | 'all-projects' | 'recycling-bin' | 'doc-group'
}

const { RangePicker } = DatePicker;

const DocProjectWapper = (props: Props, ref: any) => {
    useImperativeHandle(ref, () => ({

    }))

    const {
        Search
    } = Input;

    const {
        screenType
    } = props;

    const navigate = useNavigate();
    const routerLocation = useLocation();
    const [searchParams, setSearchParams] = useSearchParams();
    const [modal, contextHolder] = Modal.useModal();
    const addProjectModalRef = useRef<any>(null);

    const [projectList, setProjectList] = useState<DocInstance[]>([]);

    const [currentProtectlandType, setCurrentProtectlandType] = useState<'0' | '1' | '2'>(null); //全部、我创建的、我参与的
    const [currentStatus, setCurrentStatus] = useState<'1' | '2' | '3'>(null);
    const [currentSortType, setCurrentSortType] = useState<'1' | '2' | '3' | '4'>('1');
    const [currentLayoutType, setCurrentLayoutType] = useState<'card' | 'list'>('card');
    const [queryFileName, setQueryFileName] = useState('');

    const [queryForm] = Form.useForm<{ name: string; protectlandProvince: string; protectlandLevel: string, dateRange: any[] }>()
    const [queryParams, setQueryParams] = useState<{ name: string; protectlandProvince: string; protectlandLevel: string,protectlandType: null, dateRange: any[] }>({
        name: null,
        protectlandProvince: null,
        protectlandLevel: null,
        protectlandType: null,
        dateRange: []
    });
    const [pageParams, setPageParams] = useState<{ page: number, size: number }>({
        page: 1,
        size: 10,
    });

    const tableContainerRef = useRef<any>(null);
    const tableContainerSize = useReSize(tableContainerRef)

    const [totalCount, setTotalCount] = useState(0);
    const [deleteLoading, setDeleteLoading] = useState(false);
    const [resetRadomValue, setResetRandomValue] = useState('');

    //@ts-ignore
    const [layoutType, setLayoutType] = useState<'card' | 'list'>(searchParams.get('layout') ? searchParams.get('layout') : 'list');

    useEffect(() => {
        queryPorjectList();
    }, [resetRadomValue]);

    const copyProjectModalRef = useRef(null);

    const protectlandTypeList = [
        {
            label: "全部",
            value: '0',
        },
        {
            label: "自然保护区",
            value: '1',
        },
        {
            label: "国家公园",
            value: '2',
        },
        {
            label: "自然公园",
            value: '3',
        }
    ]
    const statusList = [
        // {
        //     name: "进行中",
        //     id: '1',
        // },
        // {
        //     name: "修订中",
        //     id: '2',
        // },
        // {
        //     name: "已定稿",
        //     id: '3',
        // }
    ]

    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const {
            pathname
        } = routerLocation;
        console.log("routerLocation---->", routerLocation)
        if (!pathname.includes(screenType)) {
            return;
        }
        const _protectlandType = searchParams.get('protectlandType') ? searchParams.get('protectlandType') : '0';
        const _status = searchParams.get('status-code');
        const _sortType = searchParams.get('sort-type');
        const _layoutType = searchParams.get('layout-type');
        // console.log("监听--->", _belongType);
        // console.log("监听--->", _status)
        //@ts-ignore
        setCurrentStatus(_status);
        //@ts-ignore
        setCurrentProtectlandType(_protectlandType);
        //@ts-ignore
        setCurrentSortType(_sortType);
        //@ts-ignore
        setCurrentLayoutType(_layoutType);
        queryPorjectList();
    }, [pageParams, searchParams, routerLocation])

    const queryPorjectList = () => {
        let params = {
            page: pageParams.page,
            size: pageParams.size,
            startTime: queryParams.dateRange.length ? queryParams.dateRange[0] : '',
            endTime: queryParams.dateRange.length ? queryParams.dateRange[1] : '',
            params: {},
        }
        const sectionalizationId = searchParams.get('sectionalization-id');
        if (!isEmpty(queryParams.name)) {
            //@ts-ignore
            params.params.name = queryParams.name;
        }
        if (!isEmpty(sectionalizationId)) {
            //@ts-ignore
            params.params.sectionalizationId = sectionalizationId;
        }
        if (!isEmpty(queryParams.protectlandProvince)) {
            //@ts-ignore
            params.params.protectlandProvince = queryParams.protectlandProvince;
        }
        if (!isEmpty(queryParams.protectlandLevel)) {
            //@ts-ignore
            params.params.protectlandLevel = queryParams.protectlandLevel;
        }
        const _protectlandType = searchParams.get('protectlandType');
        if (!isEmpty(_protectlandType) && _protectlandType !== '0') {
            const findProtectlandType = protectlandTypeList.find(item => {
                return item.value === _protectlandType;
            })
            //@ts-ignore
            params.params.protectlandType = findProtectlandType.name;
        }
        const _status = searchParams.get('status-code');
        if (!isEmpty(_status)) {
            //@ts-ignore
            params.params.status = _status;
        }
        // const _sortType = searchParams.get('sort-type');
        // if (!isEmpty(_sortType)) {
        //     //@ts-ignore
        //     params.sortType = _sortType;
        // }
        if (screenType == 'recently-opened') {
            //@ts-ignore
            params.params.lastManyDays = '3';
        } else if (screenType == 'recycling-bin') {
            //@ts-ignore
            params.params.isDeleted = true;
        }
        setLoading(true);
        systemApi.getProjectList(params)
            .then(res => {
                console.log("res", res)
                setLoading(false);
                setProjectList(addKeyToList(res.data.list));
                //@ts-ignore
                setTotalCount(res.data.pager.total)
            })
            .catch(err => {
                setLoading(false);
                console.log("err", err)
            })
    }

    const handleOpenAddProjectModal = () => {
        addProjectModalRef.current.openModal();
    }

    const _onFinish = () => {
        toastShort('success', '操作成功');
        queryPorjectList();
    }

    const handleJumpToEdit = (project: DocInstance) => {
        const {
            pathname,
            search
        } = routerLocation;
        localStorage.setItem('formEditPagePath', pathname + search);
        // navigate('/edit?docId=' + project.id + '&screen=excel')
        handleJumpEditPage('/edit?docId=' + project.id + '&screen=topic' + '&sidetab=allTopic');
    }

    const switchProtectlandType = (typeId) => {
        if(typeId == undefined){
            typeId = null;
        }
        // console.log("typeId--->", typeId)
        setCurrentProtectlandType(typeId)
        handleSetSearchParams('protectlandType', typeId)
    }

    const switchStatus = (status, index) => {
        setCurrentStatus(status.id)
        handleSetSearchParams('status-code', status.id)
    }

    const handleSetSearchParams = (key: string, value: string) => {
        let newParams = new URLSearchParams(searchParams.toString());
        newParams.set(key, value);
        setSearchParams(deepCloneV2(newParams));
    }

    // const renderSwitchBar = () => {
    //     switch (screenType) {
    //         case 'doc-group':
    //         case 'all-projects':
    //             return (
    //                 <>
    //                     <div className='flex-row side-bar-content-top-switch'>
    //                         {
    //                             renderBelongType()
    //                         }
    //                     </div>
    //                     {/* <div className='side-bar-content-top-switch-border'></div>
    //                     <div className='flex-row side-bar-content-top-switch'>
    //                         {
    //                             renderStatus()
    //                         }
    //                     </div> */}
    //                 </>
    //             )
    //             break;
    //         case 'recently-opened':
    //             return (
    //                 <div className='flex-row side-bar-content-top-switch'>
    //                     {
    //                         renderBelongType()
    //                     }
    //                 </div>
    //             )
    //             break;
    //         case 'recycling-bin':
    //             return (
    //                 <div className='flex-row side-bar-content-top-switch'>
    //                     <div className='side-bar-content-top-switch-item active'>最近删除(30天)</div>
    //                 </div>
    //             )
    //             break;
    //         default:
    //             break;
    //     }
    // }

    const sortMenuList: MenuProps['items'] = [
        {
            key: '1',
            label: '创建时间',
            icon: <ClockCircleOutlined />
        },
        {
            key: '2',
            label: '更新时间',
            icon: <ClockCircleOutlined />
        },
        {
            key: '3',
            label: '规划名称',
            icon: <FileTextOutlined />
        },
    ]

    const adaptSortTypeName = () => {
        try {
            const findSortMenuItem = sortMenuList.find(ele => {
                return ele.key == currentSortType;
            })
            //@ts-ignore
            return findSortMenuItem.label;
        } catch (e) {
            return '创建时间'
        }
    }

    const onClickSortItem: MenuProps['onClick'] = ({ key }) => {
        //@ts-ignore
        setCurrentSortType(key);
        handleSetSearchParams('sort-type', key);
    }


    const switchCurrentLayoutType = () => {
        let newLayoutType = currentLayoutType == 'card' ? 'list' : 'card';
        handleSetSearchParams('layout-type', newLayoutType);
        //@ts-ignore
        setCurrentLayoutType(newLayoutType)
    }


    const onQueryFileNameTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        setQueryFileName(getChangeEventValue(e));
        if (isEmpty(getChangeEventValue(e))) {
            handleSearch();
        }
    }

    const handleResetQueryParams = () => {
        setQueryParams({
            name: "",
            protectlandProvince: "",
            protectlandLevel: "",
            protectlandType: null,
            dateRange: []
        })
        queryForm.setFieldValue('name', null);
        queryForm.setFieldValue('protectlandProvince', null);
        queryForm.setFieldValue('protectlandLevel', null);
        queryForm.setFieldValue('dataRange', null);
        setResetRandomValue(Math.random().toString());
    }

    const handleSearch = () => {
        setPageParams({ ...pageParams })
    }

    const handleOpenEditModal = (project: DocInstance) => {
        addProjectModalRef.current.openModal(project);
    }

    const handleOpenCopyModal = (project: DocInstance) => {
        copyProjectModalRef.current.openModal(project);
    }

    const comfirmToDeleteTopicTemplate = (project: DocInstance) => {
        setDeleteLoading(true);
        let params = {
            ids: [project.id]
        }
        systemApi.deleteProject(params)
            .then(res => {
                setDeleteLoading(false);
                _onFinish();
            })
            .catch(err => {
                setDeleteLoading(false);
                toastShort('error', commonErrorMsg)
            })
    }

    const deleteDoc = (docInstance: DocInstance) => {
        modal.confirm({
            title: '温馨提示',
            icon: <ExclamationCircleOutlined />,
            content: '确认删除此规划报告？此操作不可撤销',
            okText: '确认',
            cancelText: '取消',
            centered: true,
            onOk: () => comfirmToDeleteTopicTemplate(docInstance),
            okButtonProps: { loading: deleteLoading }
        });
    }

    const handleCopyProject = (docInstance: DocInstance) => {
        copyProjectModalRef.current.openModal(docInstance)
    }

    const recoverProject = (docInstance: DocInstance) => {
        modal.confirm({
            title: '温馨提示',
            icon: <ExclamationCircleOutlined />,
            content: '确认将此规划报告从回收站放回原处？',
            okText: '确认',
            cancelText: '取消',
            centered: true,
            onOk: () => comfirmToRecoverTopicTemplate(docInstance),
            okButtonProps: { loading: deleteLoading }
        });
    }

    const comfirmToRecoverTopicTemplate = (project: DocInstance) => {
        setDeleteLoading(true);
        let params = project;
        params.isDeleted = false;
        systemApi.updateProjectBaseInfo(params)
            .then(res => {
                setDeleteLoading(false);
                _onFinish();
            })
            .catch(err => {
                setDeleteLoading(false);
                toastShort('error', commonErrorMsg)
            })
    }

    const columns: ColumnsType<DocInstance> = [
        {
            title: '文件名称',
            dataIndex: 'name',
            key: 'name',
            render: (value, record, index) => {
                return (
                    <div
                        className='flex-row project-table-name'
                        title='编制规划'
                        onClick={() => handleJumpToEdit(record)}
                    >
                        <FileTextOutlined style={{ fontSize: 18 }} />&nbsp;{record.name}
                    </div>
                )
            },
            sorter: {
                compare: (a, b) => getAZindex(Pinyin.getWordsCode(a.name)[0]) > getAZindex(Pinyin.getWordsCode(b.name)[0]) ? 1 : -1.
            },
        },
        {
            title: '创建者',
            key: 'createUserName',
            dataIndex: 'createUserName',
            render: (value, record, index) => {
                return <span style={{ fontWeight: '700' }}>{record.createUserName}</span>
            },
            sorter: {
                compare: (a, b) => getAZindex(Pinyin.getWordsCode(a.createUserName)[0]) > getAZindex(Pinyin.getWordsCode(b.createUserName)[0]) ? 1 : -1,
            },
        },
        {
            title: '创建时间',
            key: 'createDate',
            dataIndex: 'createDate',
            render: (value, record, index) => {
                return <span>{formatTime(record.createDate)}</span>
            },
            sorter: {
                compare: (a, b) => Number(a.createDate) > Number(b.createDate) ? 1 : -1,
            },
        },
        {
            title: '更新时间',
            key: 'updateDate',
            dataIndex: 'updateDate',
            render: (value, record, index) => {
                return <span>{formatTime(record.updateDate)}</span>
            },
            sorter: {
                compare: (a, b) => Number(a.updateDate) > Number(b.updateDate) ? 1 : -1,
            },
        },
        {
            title: '操作',
            key: 'option',
            dataIndex: 'option',
            align: 'center',
            fixed: 'right',
            render: (value, record, index) => {
                return (
                    <Space>
                        <Tooltip
                            title={"编制规划"}
                        >
                            <Button
                                type={'text'}
                                icon={<Editor theme="outline" size="20" fill="#0f6432" strokeWidth={4} />}
                                onClick={() => handleJumpToEdit(record)}
                                disabled={screenType == 'recycling-bin'}
                            />
                        </Tooltip>
                        {
                            !checkIsTempAccount() ?
                                <Tooltip
                                    title={"创建副本"}
                                >
                                    <Button
                                        type={'text'}
                                        icon={<CopyOutlined style={{ fontSize: 18, color: '#0f6432' }} />}
                                        onClick={() => handleCopyProject(record)}
                                        disabled={screenType == 'recycling-bin'}
                                    />
                                </Tooltip>
                                :
                                null
                        }
                        <Tooltip
                            title={"基本信息"}
                        >
                            <Button
                                type={'text'}
                                icon={<InfoCircleOutlined style={{ fontSize: 18, color: '#ff9c6e' }} />}
                                onClick={() => handleOpenEditModal(record)}
                                disabled={screenType == 'recycling-bin'}
                            >

                            </Button>
                        </Tooltip>
                        {
                            screenType !== 'recycling-bin' ?
                                <Tooltip
                                    title={"删除规划"}
                                >
                                    <Button
                                        type={'text'}
                                        icon={<Delete theme="outline" size="19" fill="#FF0000" strokeWidth={3} />}
                                        onClick={() => deleteDoc(record)}
                                        danger
                                    >
                                    </Button>
                                </Tooltip>
                                :
                                <Tooltip
                                    title={"放回原处"}
                                >
                                    <Button
                                        type={'text'}
                                        icon={<FileSyncOutlined />}
                                        onClick={() => recoverProject(record)}
                                    >
                                    </Button>
                                </Tooltip>

                        }
                    </Space>
                )
            }
        },
    ];

    const onTableChange = (pagination, filters, sorter, extra) => {
        console.log("onTableChange--->", sorter)
    }

    const onPaginationChange = (page: number, pageSize: number) => {
        let _pageParams = pageParams;
        _pageParams.size = pageSize;
        _pageParams.page = page;
        setPageParams({ ..._pageParams });
    }

    const onDateRangeChange = (dates: any) => {
        const startTimeStamp = dates[0] ? Math.floor(dates[0].valueOf() / 1000) : null;
        const endTimeStamp = dates[1] ? Math.floor(dates[1].valueOf() / 1000) : null;
        console.log('Start Time:', startTimeStamp, 'End Time:', endTimeStamp);
        let _queryParams = queryParams;
        _queryParams.dateRange = [startTimeStamp, endTimeStamp];
        setQueryParams({ ..._queryParams })
    }

    const onProtectlandLevelChange = (e: string) => {
        console.log("onProtectlandLevelChange--->", e)
        let _queryParams = queryParams;
        _queryParams.protectlandLevel = e;
        setQueryParams({ ..._queryParams })
    }

    const onNameTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        console.log("onNameTextChange--->", e)
        let _queryParams = queryParams;
        _queryParams.name = getChangeEventValue(e);
        setQueryParams({ ..._queryParams })
    }

    const onProtectlandProvinceChange = (e: string) => {
        let _queryParams = queryParams;
        _queryParams.protectlandProvince = e;
        setQueryParams({ ..._queryParams })
    }

    const switchLayoutType = () => {
        let newLayoutType = layoutType == 'card' ? 'list' : 'card';
        handleSetSearchParams('layout', newLayoutType);
        //@ts-ignore
        setLayoutType(newLayoutType)
    }

    return (
        <div className='flex-col side-bar-content'>
            <div className='flex-row side-bar-content-top'>
                <Tooltip
                    title="切换卡片/列表展示"
                >
                    <Button
                        icon={layoutType == 'card' ? <i style={{ fontSize: '24px' }} className='iconfont-1 ghzs-gray-qiapianxingshi' /> : <UnorderedListOutlined style={{ fontSize: 24 }} />}
                        type={'text'}
                        onClick={switchLayoutType}
                        className='side-bar-content-top-right-item'
                        style={{ marginRight: 10 }}
                    />
                </Tooltip>
                <Button
                    icon={<PlusOutlined />}
                    type={'primary'}
                    disabled={screenType == 'recycling-bin'}
                    onClick={handleOpenAddProjectModal}
                >
                    新增
                </Button>
                <div className='flex-row custom-form-item'>
                    <div className='custom-form-item-title'>保护地类型：</div>
                    <Select
                        placeholder={"请选择"}
                        className='no-bg-select'
                        style={{ width: 112, backgroundColor: 'transparent' }}
                        options={protectlandTypeList}
                        value={queryParams.protectlandType}
                        defaultValue={queryParams.protectlandType}
                        onChange={switchProtectlandType}
                        allowClear
                    />
                </div>
                <div className='flex-row custom-form-item'>
                    <div className='custom-form-item-title'>省份：</div>
                    <Select
                        placeholder={"请选择省份"}
                        className='no-bg-select'
                        style={{ width: 112, backgroundColor: 'transparent' }}
                        options={provinceList}
                        value={queryParams.protectlandProvince}
                        onChange={onProtectlandProvinceChange}
                        showSearch
                        filterOption={(input, option) =>
                            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                    />
                </div>
                <div className='flex-row custom-form-item'>
                    <div className='custom-form-item-title'>级别：</div>
                    <Select
                        placeholder={"请选择级别"}
                        className='no-bg-select'
                        style={{ width: 112, backgroundColor: 'transparent' }}
                        popupMatchSelectWidth={false}
                        options={[
                            { value: '1', label: '国家级' },
                            { value: '2', label: '省（自治区、直辖市）级' },
                            { value: '3', label: '市（自治州）级' },
                            { value: '4', label: '县（自治县、旗、县级市）级' },
                        ]}
                        value={queryParams.protectlandLevel}
                        onChange={onProtectlandLevelChange}
                        allowClear
                    />
                </div>
                <div className='flex-row custom-form-item'>
                    <div className='custom-form-item-title'>创建日期：</div>
                    <RangePicker
                        style={{ width: 238, backgroundColor: 'transparent' }}
                        placeholder={['开始日期', '结束日期']}
                        onChange={onDateRangeChange}
                        allowClear
                    />
                </div>
                <div className='flex-row custom-form-item'>
                    <div className='custom-form-item-title'>规划名称：</div>
                    <Input
                        placeholder={'搜索规划报告名称'}
                        type={'primary'}
                        value={queryParams.name}
                        onChange={onNameTextChange}
                        style={{ width: 152, backgroundColor: 'transparent' }}
                        allowClear
                    />
                </div>
                <Button
                    type={"primary"}
                    icon={<SearchOutlined />}
                    style={{ marginLeft: 12 }}
                    onClick={handleSearch}
                    ghost
                >
                    查询
                </Button>
            </div>
            <div
                className='side-bar-content-scroll'
            >
                <div className='flex-col home-page-table-container'>
                    <div
                        ref={tableContainerRef}
                        className='home-page-table-content'
                    >
                        {
                            layoutType == 'card' ?
                                <div className='flex-row home-page-table-content-card'>
                                    {
                                        projectList && projectList.map((item, index) => {
                                            return (
                                                <div
                                                    key={index + ''}
                                                    className='flex-row project-card'
                                                    onClick={() => handleJumpToEdit(item)}
                                                >
                                                    <img
                                                        src={require('./../../../assets/image/project-doc-icon.png')}
                                                        className='project-card-icon'
                                                    />
                                                    <div className='flex-col project-card-right'>
                                                        <div className='single-line-text project-card-title'>{item.name}</div>
                                                        <div className='project-card-date'>{formatTime(item.createDate)}</div>
                                                    </div>
                                                </div>
                                            )
                                        })
                                    }
                                </div>
                                :
                                <Table
                                    columns={columns}
                                    dataSource={projectList}
                                    onChange={onTableChange}
                                    style={{ width: '100%' }}
                                    pagination={false}
                                    loading={loading}
                                    className='doc-list-table'
                                    scroll={{ x: 'max-content', y: getSingleTdTableHeight(tableContainerSize.height) }}
                                />
                        }
                    </div>
                    <div className='flex-row home-page-table-pagination'>
                        <Pagination
                            total={totalCount}
                            pageSize={pageParams.size}
                            current={pageParams.page}
                            showSizeChanger
                            showQuickJumper
                            showTotal={(total) => `共${total} 项`}
                            locale={{
                                items_per_page: '/页',
                                jump_to: '跳转到',
                                page: '页'
                            }}
                            onChange={onPaginationChange}
                        />
                    </div>
                </div>
            </div>
            <AddProjectModal
                ref={addProjectModalRef}
                onFinish={_onFinish}
            />
            <CopyProjectModal
                ref={copyProjectModalRef}
                onFinish={_onFinish}
            />
            {/* <LoadingWapper
                loading={loading}
            /> */}
            {contextHolder}
        </div>
    )
}

export default forwardRef(DocProjectWapper);